package com.jt.service;

import com.jt.mapper.FileMapper;
import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileMapper fileMapper;

    private String rootDir = "F:/hx/project3/images";
    private String rootUrl = "http://image.jt.com";

    //删除文件  需要文件全路径
    @Override
    public void deleteFile(String virtualPath) {
        String localPath = rootDir + virtualPath;
        File file = new File(localPath);
        if(file.exists()){ //如果文件存在,则删除
            file.delete();
        }
    }

    @Override
    public ImageVO upload(MultipartFile file) {

        // 获取图片名称，全部转小写
        String originalFilename = file.getOriginalFilename().toLowerCase();
        if (!originalFilename.matches("^.+\\.(jpg|png|gif)$")) {
            return null;
        }
        // 判断文件是否为图片
        try {
            // java 拓展包提供的操作 图片的API
            BufferedImage read = ImageIO.read(file.getInputStream());
            // 通过文件属性判断是否为图片
            int height = read.getHeight();
            int width = read.getWidth();
            if (height == 0 || width == 0) {
                return null;
            }
            String path = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String fileDir = rootDir + path;
            File file1 = new File(fileDir);
            if (!file1.exists()){
                file1.mkdirs();
            }
            // 防止重名
            String s = java.util.UUID.randomUUID().toString();
            int i = originalFilename.lastIndexOf(".");
            String substring = originalFilename.substring(i);
            originalFilename = s + substring;
            String fullPath = fileDir + originalFilename;
            file.transferTo(new File(fullPath));

            String virtualPath = path + originalFilename;
            String urlPath = rootUrl +virtualPath;
            System.out.println(urlPath);
            ImageVO imageVO = new ImageVO(virtualPath,urlPath,originalFilename);
            return imageVO;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
